package com.lcf.app.jwt.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.lcf.app.jwt.common.CurrentUser;
import com.lcf.app.jwt.config.JwtHelper;
import com.lcf.app.jwt.exception.MyTokenException;
import com.lcf.app.jwt.model.User;
import com.lcf.common.web.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ChenFei
 * @date 2022/1/18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtTokenInterceptor implements HandlerInterceptor {

    private final JwtHelper jwtHelper;

    //拦截器逻辑
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        log.info("拦截器-------------preHandle : {}", request.getRequestURI());
        String token = request.getHeader(jwtHelper.getHeaderName());
        if (StrUtil.isBlank(token)) {
            writeJson(response, Result.fail(jwtHelper.getHeaderName() + " ：不能为空"));
            return false;
        }
        try {
            User user = jwtHelper.verify(token, User.class);
            CurrentUser.set(user);//给当前线程设置用户信息,方便后边获取
        } catch (MyTokenException e) {
            writeJson(response, Result.fail(e.getMessage()));
            return false;
        }
        return true;
    }

    /**
     * 向前端返回json数据
     *
     * @param response
     * @param result
     * @throws IOException
     */
    private void writeJson(HttpServletResponse response, Object result) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(result));
        writer.flush();
        writer.close();
    }
}
